package com.by.service.impl;

import com.by.bean.Car;
import com.by.service.CarService;
import com.by.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

//@Service
public class CarServiceImpl implements CarService {
    @Autowired
    RedisUtils redisUtils;

    /**
     * 使用hash命令存取
     * @param car
     */
    @Override
    public void addCar(Car car) {
        String key = "user:id:1:goods:"+car.getId();
        Object num =redisUtils.hget(key, "num");
        if (num == null){
            //说明购物车中没有该商品，直接存入
            redisUtils.hset(key, "id", car.getId());
            redisUtils.hset(key, "name", car.getName());
            redisUtils.hset(key, "price", car.getPrice());
            redisUtils.hset(key, "num", car.getNum());
        }else{
            //说明购物车中有该商品，修改数量
            Integer tmp = Integer.parseInt(num.toString());
            tmp++;
            redisUtils.hset(key, "num", tmp);

        }
    }

    @Override
    public List<Car> getCarList() {
        List<Car> list = new ArrayList<Car>();
        //获取该用户所有商品的key
        Set<String> keys = redisUtils.keys("user:id:1:*");
        Iterator<String> it = keys.iterator();
        while (it.hasNext()){
            String key = it.next();//一个商品的key
            Object id = redisUtils.hget(key, "id");
            Object name = redisUtils.hget(key, "name");
            Object price = redisUtils.hget(key, "price");
            Object num = redisUtils.hget(key, "num");
            list.add(new Car(Integer.parseInt(id.toString()), name.toString(), Double.parseDouble(price.toString()), Integer.parseInt(num.toString())));

        }        return list;
    }
}
